/** * 基础信息-产品管理 */
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">基础信息</el-breadcrumb-item>
      <el-breadcrumb-item>产品管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search" align="left">
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">新增</el-button>
        <el-button size="small" type="danger" @click="batchDel()">批量删除</el-button>
      </el-form-item>
      <el-form-item label="搜索:">
        <el-input size="small" v-model="formInline.name" placeholder="产品名称" class="searchInput"/>
        <el-select size="small" v-model="formInline.production_brand" placeholder="选择品牌" class="searchSelect">
            <el-option v-for="item in selectOption.brandOption" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
        <el-select size="small" v-model="formInline.production_type" placeholder="选择分类" class="searchSelect">
            <el-option v-for="item in selectOption.typeOption" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
        <el-select size="small" v-model="formInline.warehousename" placeholder="选择仓库" class="searchSelect">
            <el-option v-for="item in selectOption.warehouseOption" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
        <el-select size="small" v-model="formInline.isEnable" placeholder="是否启用" class="searchSelect">
            <el-option label="启用" value="1"/>
            <el-option label="未启用" value="2"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="getdata()">搜索</el-button>
        <el-button size="small" type="danger" @click="clearConditon()">重置</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" :data="listData" highlight-current-row border :row-key="getRowKeys" ref="multipleSelectable"
    @selection-change="handleSelectionChange" style="width: 100%" @sort-change="sortChange">
      <el-table-column align="center" type="selection" width="40" :reserve-selection="true"/>
      <el-table-column align="center" prop="id" label="序号" width="50"/>
      <el-table-column align="center" prop="material_code" label="产品编码" width="70"/>
      <el-table-column align="center" prop="name" label="产品名称" width="150"/>
      <el-table-column align="center" prop="production_brand" label="产品品牌" width="70"/>
      <el-table-column align="center" prop="production_type" label="产品分类" width="70"/>
      <el-table-column align="center" prop="model" label="产品型号" width="70"/>
      <el-table-column align="center" prop="mesure_unit" label="产品单位" width="70"/>
      <el-table-column align="center" prop="price" label="定价" width="70" sortable="custom"/>
      <el-table-column align="center" prop="isEndproduct" label="是否成品" width="70"/>
      <el-table-column align="center" prop="warehousename" label="存放仓库" width="100"/>
      <el-table-column align="center" prop="isEnable" label="启用" width="70">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isEnable=='1'?nshow:fshow" @change="editEnable(scope.row)" active-color="#13ce66" inactive-color="#ff4949"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="150">
        <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="deleteOne(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination :child-msg="pageparm" @callFather="callFather" align="center"/>
    <!-- 新增、编辑页面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="55%" :before-close="closeDialog">
      <el-form :inline="true" label-width="100px" :model="editForm" ref="editForm" :rules="rules">
        <el-form-item label="产品编码" prop="material_code">
          <el-input size="small" v-model="editForm.material_code" placeholder="示例：CPBM01"/>
        </el-form-item>
        <el-form-item label="产品名称" prop="name">
          <el-input size="small" v-model="editForm.name" placeholder="示例：大米65寸智能电视"/>
        </el-form-item>
        <el-form-item label="产品品牌" prop="production_brand">
          <el-select size="small" v-model="editForm.production_brand" placeholder="选择品牌" class="mySelect">
            <el-option v-for="item in selectOption.brandOption" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="产品分类" prop="production_type">
          <el-select size="small" v-model="editForm.production_type" placeholder="选择分类" class="mySelect">
            <el-option v-for="item in selectOption.typeOption" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="产品型号" prop="model">
          <el-input size="small" v-model="editForm.model" placeholder="示例：Mi65"/>
        </el-form-item>
        <el-form-item label="产品单位" prop="mesure_unit">
          <el-select size="small" v-model="editForm.mesure_unit" placeholder="选择单位" class="mySelect">
            <el-option v-for="item in selectOption.unitOption" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="定价" prop="price">
          <el-input size="small" v-model.number="editForm.price"/>
        </el-form-item>
        <el-form-item label="是否成品" prop="isEndproduct">
          <el-select size="small" v-model="editForm.isEndproduct" placeholder="是否成品" class="mySelect">
            <el-option label="成品" value="成品"/>
            <el-option label="半成品" value="半成品"/>
          </el-select>
        </el-form-item>
        <el-form-item label="存放仓库" prop="warehousename">
          <el-select size="small" v-model="editForm.warehousename" placeholder="选择仓库" class="mySelect">
            <el-option v-for="item in selectOption.warehouseOption" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-upload class="upload-demo" action="/api/aliyunOss/upload" align="right" :show-file-list="false"
        :headers="headers" :on-success="handlesuccess" :before-upload="beforeUpload">
          <el-button size="small" type="success">添加图片</el-button>
        </el-upload>
        <el-table size="small" :data="imageData" highlight-current-row border style="width: 100%">
          <el-table-column  prop="name" align="center" label="图片名" width="150"/>
          <el-table-column  prop="link" align="center" label="图片" width="200">
            <template slot-scope="scope">
              <img :src="scope.row.link"  min-width="70" height="70" />
            </template>
          </el-table-column>
          <el-table-column  prop="link" align="center" label="下载链接" width="200">
            <template slot-scope="scope">
              <a :href="scope.row.link" target="_blank">{{scope.row.link}}</a>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" min-width="100">
            <template slot-scope="scope">
                <el-button size="mini" type="primary" @click="deleteImage(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button size="small" @click="cancelDialog">取消</el-button>
        <el-button size="small" type="primary" class="title"
          @click="submitForm()">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "../../components/Pagination";
export default {
  data() {
    //校验器
    var checkCode = (rule, value, callback) => {
      //判断是否为修改
      if(this.editFormType && this.editObj.material_code===value){
        callback();
      }
      this.$axios.get("/api/production/code/"+value).then(Response => {
          if(Response.data.code==500) {
            callback();
          } 
          callback(new Error('编码已存在！'));
      })
    };
    var checkName = (rule, value, callback) => {
      //判断是否为修改
      if(this.editFormType && this.editObj.name===value){
        callback();
      }
      this.$axios.get("/api/production/name/"+encodeURI(encodeURI(value))).then(Response => {
          if(Response.data.code==500) {
            callback();
          } 
          callback(new Error('名称已存在！'));
      })
    };
    return {
      nshow: true, //switch开启
      fshow: false, //switch关闭
      // 控制编辑页面显示与隐藏
      editFormVisible: false, 
      // 控制图片删除、新增操作,false为新增框，true为修改框
      editFormType:false,
      // 进行修改的对象
      editObj:{},
      // 新增、编辑页面的标题
      title: "添加",
      // 编辑页面数据
      editForm: {
        id: "",
        material_code: "",
        name: "",
        production_brand: "",
        production_type: "",
        model: "",
        mesure_unit: "",
        price: "",
        isEndproduct: "",
        warehousename: "",
        isEnable: "",
        images:[]
      },
      // 验证规则
      rules: {
        material_code: [
          {required: true,message: '请输入产品编码', trigger: 'blur'},
          {pattern:/^[A-Za-z0-9]{6}$/, message: '请输入6位数字、字母', trigger: 'blur'},
          {validator: checkCode, trigger: 'blur' }
        ],
        name: [
          {required: true, message: '请输入产品名称', trigger: 'blur' },
          {min: 1, max: 20, message: '请输入1~20个字符', trigger: 'blur' },
          {validator: checkName, trigger: 'blur' }
        ],
        production_brand: [
          {required: true, message: '请选择产品品牌', trigger: 'blur' }
        ],
        production_type: [
          {required: true, message: '请选择产品类型', trigger: 'blur' }
        ],
        model: [
          {required: true, message: '请输入产品型号', trigger: 'blur' },
          {min: 1, max: 10, message: '请输入1~10个字符', trigger: 'blur' }
        ],
        mesure_unit: [
          {required: true, message: '请选择计量单位', trigger: 'blur' }
        ],
        price: [
          {required: true, message: '请输入定价', trigger: 'blur' },
          {type: 'number',min: 0, message: '请输入正数', trigger: 'blur' }
        ],
        isEndproduct: [
          {required: true, message: '请选择是否成品', trigger: 'blur' }
        ],
        warehousename: [
          {required: true, message: '请选择存放仓库', trigger: 'blur' }
        ],
      },
      // 搜索框数据
      formInline: {
        name: "",
        production_brand: "",
        production_type: "",
        warehousename:"",
        isEnable:"",
      },
      // 表单数据
      listData: [], 
      // 表单选择数组
      multipleSelection: [],
      // 初始化分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 5,
        total: 0,
      },
      //下拉框
      selectOption:{
        // 产品分类下拉框
        typeOption:[],
        // 产品品牌下拉框
        brandOption:[],
        // 产品单位下拉框
        unitOption:[],
        // 仓库下拉框
        warehouseOption:[],
      },
      //图片表单数据
      imageData:[],
      // 当前上传的图片名称
      imageName:"",
      // 排序字段
      orderSort:"",
      orderKey:"",
    };
  },
  // 注册组件
  components: {Pagination},

  //创建完毕
  created() {
    //渲染表单
    this.getdata();
    //渲染下拉框
    this.getSelectData();
  },
  // 获取token
  computed: {
    headers() {
      return{
        "Authorization": localStorage.getItem('logintoken')
      }
    }
  },
  // 定义方法
  methods: {
    // 清空搜索条件
    clearConditon(){
      this.formInline.name= "";
      this.formInline.production_brand= "";
      this.formInline.production_type= "";
      this.formInline.warehousename= "";
      this.formInline.isEnable="";
      this.getdata();
    },
    // 获取表单数据
    getdata() {
      let queryEntity={
        currentPage:this.pageparm.currentPage,
        pageSize:this.pageparm.pageSize,
        entity:this.formInline,
        orderSort:this.orderSort,
        orderKey:this.orderKey
      };
      this.$axios.post("/api/production/condition",queryEntity)
      .then((res) => {
          if (res.data.code == 200) {
              this.listData = res.data.data.list;
              //对总数量进行赋值
              this.pageparm.total = res.data.data.total;
          }else{
              this.$message({type: 'info',message: res.data.message})
          }
      })
      .catch(err => {
          this.$message.error('数据加载失败，请稍后再试！')
      })
    },
    // 分页插件事件
    callFather(parm) {
      this.pageparm.currentPage = parm.currentPage;
      this.pageparm.pageSize = parm.pageSize;
      this.getdata();
    },
    // 获取下拉框数据
    getSelectData(){
      this.$axios.get("/api/production/select")
        .then((res) => {
            if (res.data.code == 200) {
                this.selectOption = res.data.data;
            }else{
                this.$message({type: 'info',message: res.data.message})
            }
        })
        .catch(err => {
            this.$message.error('数据加载失败，请稍后再试！')
        })
    },
    // 排序方法
    sortChange(column) {
        if (column.order == "ascending") {
          this.orderSort = 'asc'
        } else if (column.order == "descending") {
          this.orderSort = 'desc'
        } else {
          this.orderSort = ''
        }
        this.orderKey=column.prop;
        this.getdata();
      },
    //显示新增、编辑界面
    handleEdit: function (obj) {
      this.editFormVisible = true;
      if (obj != undefined && obj != "undefined") {
        this.editObj=obj;
        this.editFormType=true;
        this.title = "修改";
        //填充数据
        this.editForm.id = obj.id;
        this.editForm.material_code = obj.material_code;
        this.editForm.name = obj.name;
        this.editForm.production_brand = obj.production_brand;
        this.editForm.production_type = obj.production_type;
        this.editForm.model = obj.model;
        this.editForm.mesure_unit = obj.mesure_unit;
        this.editForm.price = obj.price;
        this.editForm.isEndproduct = obj.isEndproduct;
        this.editForm.warehousename = obj.warehousename;
        this.editForm.isEnable = obj.isEnable;
        this.imageData=obj.images;
      } else {
        this.editFormType=false;
        this.title = "添加";
        //清空数据
        this.editForm.id = "";
        this.editForm.material_code = "";
        this.editForm.name = "";
        this.editForm.production_brand = "";
        this.editForm.production_type = "";
        this.editForm.model = "";
        this.editForm.mesure_unit = "";
        this.editForm.price = "";
        this.editForm.isEndproduct = "";
        this.editForm.warehousename = "";
        this.editForm.isEnable = "";
        this.imageData=[];
      }
    },
    // 编辑、增加页面保存方法
    submitForm() {
      // 参数验证
      this.$refs["editForm"].validate((valid) => {
        if (!valid) {
          this.$message.error("请按要求填写表单！");
        }else{
          //填充图片信息
          for(let image of this.imageData){
            image.related=this.editForm.material_code;
          }
          this.editForm.images=this.imageData;
          // 判断是修改还是新增
          if (this.editForm.id == "") {
            // 新增
            this.$axios.post("/api/production/production", this.editForm)
            .then((res) => {
                //关闭弹窗
                this.$refs["editForm"].resetFields();
                this.editFormVisible = false;
                if (res.data.code == 200) {
                    //刷新数据
                    this.getdata();
                    this.$message({
                        type: "success",
                        message: "保存成功！",
                    });
                } else {
                    this.$message({
                        type: "info",
                        message: res.data.message,
                    });
                }
            })
            .catch((err) => {
              this.editFormVisible = false;
              this.$message.error("保存失败，请稍后再试！");
            });
          } else {
            // 修改
            this.$axios.put("/api/production/production", this.editForm)
            .then((res) => {
                //关闭弹窗
                this.$refs["editForm"].resetFields();
                this.editFormVisible = false;
                if (res.data.code == 200) {
                    //刷新数据
                    this.getdata();
                    this.$message({
                        type: "success",
                        message: "保存成功！",
                    });
                } else {
                    this.$message({
                        type: "info",
                        message: res.data.message,
                    });
                }
            })
            .catch((err) => {
              this.editFormVisible = false;
              this.$message.error("保存失败，请稍后再试！");
            });
          }
        }
      });
    },
    // 删除一个
    deleteOne(obj) {
        this.$confirm("确定要删除吗?", "信息", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        })
        .then(() => {
            this.$axios.delete("/api/production/production/"+obj.id)
            .then((res) => {
              if (res.data.code == 200) {
                this.$message({
                  type: "success",
                  message: "已删除!",
                });
                this.getdata();
              } else {
                this.$message({
                  type: "info",
                  message: res.data.message,
                });
              }
            })
            .catch((err) => {
              this.$message.error("删除失败，请稍后再试！");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 批量删除
    batchDel() {
        if(this.multipleSelection.length==0){
            this.$message({
                type: "info",
                message: "请先勾选需要删除的列",
            });
            return;
        }
        this.$confirm("确定要删除吗?", "信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        })
        .then(() => {
            this.$axios.put("/api/production/production/batchDel",this.multipleSelection)
            .then((res) => {
              this.$refs.multipleSelectable.clearSelection();
              if (res.data.code == 200) {
                this.$message({
                  type: "success",
                  message: "已删除!",
                });
                this.getdata();
              } else {
                this.$message({
                  type: "info",
                  message: res.data.message,
                });
              }
            })
            .catch((err) => {
              this.$refs.multipleSelectable.clearSelection();
              this.$message.error(err.response.data.message);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 启用开关
    editEnable(obj) {
      let newObj=obj;
      newObj.isEnable=3-obj.isEnable;
      // 修改
      this.$axios.put("/api/production/production", newObj)
      .then((res) => {
          if (res.data.code == 200) {
              //刷新数据
              this.getdata();
              this.$message({
                  type: "success",
                  message: "操作成功！",
              });
          } else {
              this.$message({
                  type: "info",
                  message: res.data.message,
              });
          }
      })
      .catch((err) => {
        this.editFormVisible = false;
        this.$message.error("操作失败，请稍后再试！");
      });
    },
    // 关闭编辑、增加弹出框
    cancelDialog() {
      this.$refs["editForm"].resetFields();
      this.editFormVisible = false;
    },
    // 关闭前清空验证信息
    closeDialog(done){
      this.$refs["editForm"].resetFields();
      done();
    },
    // 处理表单多选
    handleSelectionChange(val) {
        this.multipleSelection=[];
        for(let index in val){
            this.multipleSelection[index]=val[index].id;
        }
    },
    getRowKeys(row) {
      return row.id;
    },
    // 上传前判断文件格式
    beforeUpload(file) {
      this.imageName=file.name;
      const isIMG =
        file.type === 'image/jpg' ||
        file.type === 'image/jpeg' ||
        file.type === 'image/png'
        const isLt = file.size / 1024 / 1024 <= 1
        if (!isIMG) {
          this.$message.error('上传图片只支持jpg、jpeg、png格式!')
        }
        if (!isLt) {
          this.$message.error('上传图片大小不能超过1MB!')
        }
        return  isIMG && isLt; 
    },
    //上传成功回调方法
    handlesuccess(res) {
      if (res.code == 200) {
        //如果是修改框
        if(this.editFormType){
          let image={name:this.imageName,link:res.data,related:this.editForm.material_code};
          //存入数据库
            this.$axios.post("/api/images/images", image)
            .then((res2) => {
                if (res2.data.code == 200) {
                  this.imageData.push(res2.data.data);
                    this.$message({
                        type: "success",
                        message: "保存成功！",
                    });
                } else {
                    this.$message({
                        type: "info",
                        message: res.data.message,
                    });
                }
            })
            .catch((err) => {
              this.$message.error("保存失败，请稍后再试！");
            });
        }else{
          this.imageData.push({name:this.imageName,related:this.editForm.material_code,link:res.data});
          this.$message({
            type: "success",
            message: "操作成功！",
          });
        }
      } else {
        this.$message({
            type: "info",
            message: res.message,
        });
      }
    },
    //删除图片
    deleteImage(obj){
      this.$confirm("确定要删除吗?", "信息", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        })
        .then(() => {
          //如果是修改框
          if(this.editFormType){
            this.$axios.delete("/api/images/images/"+obj.id)
            .then((res) => {
              if (res.data.code == 200) {
                //删除该行
                for(var i = 0; i < this.imageData.length; i++){
                    if(this.imageData[i].id == obj.id){
                        this.imageData.splice(i,1);
                    }
                }
                this.$message({
                  type: "success",
                  message: "已删除!",
                });
              } else {
                this.$message({
                  type: "info",
                  message: res.data.message,
                });
              }
            })
            .catch((err) => {
              this.$message.error("删除失败，请稍后再试！");
            });
          }else{
            //删除该行
            for(var i = 0; i < this.imageData.length; i++){
                if(this.imageData[i].id == obj.id){
                    this.imageData.splice(i,1);
                }
            }
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    }
  },
};
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
.mySelect{
  width: 193px;
}
.searchSelect{
  width: 100px;
}
.searchInput{
  width: 100px;
}
</style>
